﻿using ComLib.ComFun;
using CoreBroker;
using KWindow.KPageCore;
using LogLib;
using Spire.Pdf;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace IPCPages
{
    public partial class PagePhotoPrinting : PageControlBase
    {
        private ConfigDirectory _dirConfig = null;    
        private string OutputPDFFile = "";
        private bool _printingResult = false;
        private FRPhotoPrinter _printer = null;
        private FRPOption _option = new FRPOption();
        private PictureBox pictureBoxPreview = null;

        /// <summary>
        /// 选中的照片
        /// </summary>
        private TakenPhoto _thePhoto = null;

        private Image imgPrinting = null;

        private Image imgPrintingFailed = null;

        private Image imgPreview = null;

        //private Label labelTitle = null;

        private Label labelTip = null;

        public PagePhotoPrinting()
        {
            _printer = new FRPhotoPrinter();
            _dirConfig = new ConfigDirectory();           
            InitializeComponent();
            SetProcessBase(ProcessPhotoPrinting.Instance);
        }

        private void LoadConfig()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        private void GetControls()
        {
            pictureBoxPreview = GetControl<PictureBox>("pictureBoxPreview") as PictureBox;         
            labelTitle = GetControl<Label>("labelTitle") as Label;
            labelTip = GetControl<Label>("labelTip") as Label;
            imgPrinting = GetImage("Printing");
            imgPrintingFailed = GetImage("PrintingFailed");
        }

        //初始化窗体数据
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();
            LoadConfig();
        }

        public override void Close()
        {
            FileOperation.DeleteAllExeclsInDir(_dirConfig.PDFFile);
            FileOperation.DeleteAllExeclsInDir(_dirConfig.Preview);
        }

        /// <summary>
        /// 初始化窗体数据
        /// </summary>
        public override void InitData()
        {
            labelTip.Visible = false;
            _printingResult = false;
            _thePhoto = Process.GetValue<TakenPhoto>("TakenPhoto");
            if (_thePhoto == null)
            {
                Log.WriteAsync("发生了意外的错误:\n 获取选中照片失败。");
                MessageBox.Show("发生了意外的错误:\n 获取选中照片失败。");
                Process.ToHome();
                return;
            }
        }

        /// <summary>
        /// 保存窗体数据(窗体本次做完后, 进入下一步之前)
        /// </summary>
        public override void UpdateData()
        {
            Process.SetValue("PrintingResult", _printingResult);
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            pictureBoxPreview.Image = null;         
            _thePhoto = null;
            OutputPDFFile = "";
            if (imgPreview != null)
            {
                imgPreview.Dispose();
                imgPreview = null;
            }
        }

        private void OnPrinting()
        {
            string PhotoName = Process.GetValue<string>("PhotoSerialNumber");
            string PhotoPath = _thePhoto.DestImagePath;
            if(_printer.Print(PhotoName, PhotoPath))
            {
                OnPrintCompleted();
            }
            else
            {
                OnPrintFailed(_printer.ErrorMessage);
            }
        }

        public override void StartWork()
        {
            if(_option.EnableChoosePrint)
            {
                Speak("请选择是否打印照片");
                FormChoosing form = new FormChoosing();
                if(form.ShowDialog() == DialogResult.No)
                {
                    Log.WriteAsync("用户不打印照片，进入下一页.");
                    UpdateData();
                    ClearData();
                    Process.ToNext();
                    return;
                }
            }
            Speak("正在打印照片，请稍候");
            SetTips("正在打印照片，请稍候");
            SetShowingImage(imgPrinting, PictureBoxSizeMode.StretchImage);
            OnPrinting();
        }    

        public override void StopWork()
        {
            base.StopWork();
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            if (!_printingResult)
            {
                StopWork();
                if (Process.Job != null)
                {
                    Process.Job.Cancel("倒计时结束，操作未完成，取消拍照.");
                }
                Process.ToHome();              
            }
            else
            {
                UpdateData();
                ClearData();
                Process.ToNext();
            }
        }

        private void GetPreviewImage()
        {
            string photoName = Process.GetValue<string>("PhotoSerialNumber");
            string previewFile = string.Format("{0}\\{1}.png", _dirConfig.Preview, photoName);         
            //Open pdf document
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(OutputPDFFile);
            //Save to images
            imgPreview = doc.SaveAsImage(0, 300, 300);
            imgPreview.RotateFlip(RotateFlipType.Rotate90FlipNone);           
            doc.Close();                 
        }

        private void OnPrintCompleted()
        {
            _printingResult = true;
            string msg = string.Format("打印照片完成.");
            Log.WriteAsync(msg);
            //OutputPDFFile = _printer.OutPDFFile;
            //GetPreviewImage();
            Action handler = () =>
            {
                labelTip.Visible = true;
                //SetShowingImage(imgPreview, PictureBoxSizeMode.Zoom);
                StartCountdown();
            };
            this.Invoke(handler);  
        }

        private void OnPrintFailed(string error)
        {
            string msg = string.Format("照片打印失败: \n{0}", error);
            Log.WriteAsync(msg);
            Action<string> handler = (e) =>
            {
                SetShowingImage(imgPrintingFailed, PictureBoxSizeMode.CenterImage);
                SetTips(msg);
                StartCountdown();
            };
            this.Invoke(handler, msg);
        }

        private void SetShowingImage(Image img, PictureBoxSizeMode mode)
        {
            pictureBoxPreview.SizeMode = mode;
            pictureBoxPreview.Image = img;          
        }

        private void SetTips(string content)
        {
            labelTitle.Text = content;
            int w = labelTitle.Width;
            int x = (this.Width - w) / 2;
            labelTitle.Left = x;
        }

    }
}
